package com.fasttreatment.zzr.demo.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.fasttreatment.zzr.demo.model.NetEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by zzr on 17/1/18.
 * 网络监听
 */

public class NetReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //获取网络连接管理器
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            //获取网络联系信息
            NetworkInfo mobWorkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);   //手机流量连接
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);     //Wifi连接

            if ((mobWorkInfo != null && mobWorkInfo.isConnected()) || (wifiNetInfo != null && wifiNetInfo.isConnected())) {
                //说明有网络连接   1表示有网络连接  2 表示没有网络连接
                int state = (mobWorkInfo != null && mobWorkInfo.isConnected()) || (wifiNetInfo != null && wifiNetInfo.isConnected()) ? 1 : 2;
                EventBus.getDefault().post(new NetEvent(state, "网络已连接"));

            } else {
                //没有网络不进行处理
            }
        }
    }
}
